#define _CRT_SECURE_NO_WARNINGS 1
#include"cmp.h"

int int_cmp(const void* p1, const void* p2)
{
	return *(int*)p1 - *(int*)p2;
}

int cmp_strcmp(const void* p1, const void* p2)
{
	return *(char*)p1 - *(char*)p2;
}

int cmp_stu_by_age(const void* p1, const void* p2)
{
	return ((struct Stu*)p1)->age - ((struct Stu*)p2)->age;
}

int cmp_stu_by_name(const void* p1, const void* p2)
{
	return strcmp(((struct Stu*)p1)->name, ((struct Stu*)p2)->name);
}

void Swap(char* p1, char* p2, size_t size)
{
	int i = 0;
	for (i = 0; i < size; i++)
	{
		char tmp = *(p1 + i);
		*(p1 + i) = *(p2 + i);
		*(p2 + i) = tmp;
	}

}

void bubble_sort(void* base, size_t count, size_t size, int(*cmp)(const void*, const void*))
{
	size_t i, j = 0;

	for (i = 0; i < count - 1; i++)
	{
		for (j = 0; j < count - 1 - i; j++)
		{
			if (cmp((char*)base + j * size, (char*)base + (j + 1) * size) > 0)
			{
				Swap((char*)base + j * size, (char*)base + (j + 1) * size, size);
			}
		}
	}
}

void test1()
{
	int arr1[] = { 8,7,6,5,2,4,1,3,9,0 };
	int i = 0;
	bubble_sort(arr1, sizeof(arr1) / sizeof(arr1[0]), sizeof(arr1[0]), int_cmp);
	for (i = 0; i < sizeof(arr1) / sizeof(arr1[0]); i++)
	{
		printf("%d ", arr1[i]);
	}
	printf("\n\n");
}

void test2()
{
	struct Stu s[] = { {"zhangsan",20},{"lisi",15},{"wangwu",40} };
	bubble_sort(s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), cmp_stu_by_age);
}

void test3()
{
	struct Stu s[] = { {"zhangsan",20},{"lisi",15},{"wangwu",40} };
	bubble_sort(s, sizeof(s) / sizeof(s[0]), sizeof(s[0]), cmp_stu_by_name);
}

void test4()
{
	char arr3[] = "zxbgadefasw";
	bubble_sort(arr3, sizeof(arr3) / sizeof(arr3[0]), sizeof(arr3[0]), cmp_strcmp);
	int i = 0;
	for (i = 0; i < sizeof(arr3) / sizeof(arr3[0]); i++)
	{
		printf("%c ", arr3[i]);
	}
	printf("\n");
}